package cn.tedu.micro.demo.common.service;

import cn.tedu.micro.demo.common.feign.CartFeignClient;
import cn.tedu.micro.demo.common.feign.StockFeignClient;
import cn.tedu.micro.demo.common.mapper.OrderMapper;
import cn.tedu.micro.demo.common.pojo.po.OrderPO;
import cn.tedu.micro.demo.common.pojo.po.StockPO;
import cn.tedu.micro.demo.common.protocol.JsonResult;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;

@Service
public class OrderServiceImpl implements OrderService{
//    @Autowired
//    private CartMapper cartMapper;
    @Autowired
    private CartFeignClient cartFeignClient;
    @Autowired
    private OrderMapper orderMapper;
//    @Autowired
//    private StockMapper stockMapper;
    @Autowired
    private StockFeignClient stockFeignClient;
    @Override
    public Boolean submitOrder(Integer userId, String productCode, Integer count) {
//        扣减库存，原库存1000， count 扣减掉
//        UpdateWrapper<StockPO> updateWrapper = new UpdateWrapper<>();
//      可以封装set语句，queryWrapper只能封装where条件
//        updateWrapper.eq("product_code",productCode);
//        updateWrapper.setSql("stock=stock-" + count);
////        入参的第一个值，是一个stockPo的对象，使用对象的非空属性拼接set
        stockFeignClient.updateStock(productCode,count);
//        int update = stockMapper.update(null, updateWrapper);
////判断update是否更新成功，
////        成功则扣减，失败则返回false
//        if (update==0){
//            return false;
//        }
//        JsonResult<Boolean> booleanJsonResult = stockFeignClient.submitOrder(userId, productCode, count);
//        if (!booleanJsonResult.getData()){
//            return false;
//        }
//        生成订单，封装OrderPO 写入数据库
        OrderPO orderPO = new OrderPO();
        orderPO.setCount(count);
        orderPO.setUserId(userId);
        orderPO.setProductCode(productCode);
//        订单号，保证唯一，使用uuid
        orderPO.setOrderNo(UUID.randomUUID().toString());
        orderMapper.insert(orderPO);
//        3 根据userId 和productCode 删除购物车数据
        //delete from cart_tbl where user_id=#{userId} and product_code=#{productCode}
        QueryWrapper wrapper = new QueryWrapper<>();
        wrapper.eq("user_id",userId);
        wrapper.eq("product_code",productCode);
//        cartMapper.delete(wrapper);
        cartFeignClient.deleteCart(productCode,userId);
        return true;
    }
}
